const app = getApp()

Page({
  data: {
    examId: null,
    recordId: null,
    exam: {},
    questions: [],
    currentIndex: 0,
    currentQuestion: null,
    selectedAnswers: {},
    remainingTime: 0,
    totalTime: 0,
    timer: null,
    showSubmitDialog: false,
    showTimeUpDialog: false,
    loading: true
  },

  onLoad(options) {
    const { exam_id, record_id } = options
    this.setData({ 
      examId: exam_id,
      recordId: record_id
    })
    
    this.loadExamQuestions()
  },

  onUnload() {
    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
  },

  onHide() {
    // 页面隐藏时暂停计时
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
  },

  onShow() {
    // 页面显示时恢复计时
    if (this.data.remainingTime > 0 && !this.data.timer) {
      this.startTimer()
    }
  },

  // 加载考试题目
  loadExamQuestions() {
    wx.showLoading({ title: '加载题目中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/exams/${this.data.examId}/questions`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const { exam, questions, remaining_time } = res.data.data
          
          this.setData({
            exam: exam,
            questions: questions,
            currentQuestion: questions[0],
            remainingTime: remaining_time,
            totalTime: exam.time_limit * 60,
            loading: false
          })

          // 开始计时
          this.startTimer()
          
          wx.hideLoading()
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载考试题目失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        wx.hideLoading()
      }
    })
  },

  // 开始计时器
  startTimer() {
    const timer = setInterval(() => {
      const remainingTime = this.data.remainingTime - 1
      
      if (remainingTime <= 0) {
        clearInterval(timer)
        this.setData({ 
          remainingTime: 0,
          showTimeUpDialog: true
        })
      } else {
        this.setData({ remainingTime })
      }
    }, 1000)

    this.setData({ timer })
  },

  // 选择选项
  selectOption(e) {
    const optionKey = e.currentTarget.dataset.option
    const currentIndex = this.data.currentIndex
    const currentQuestion = this.data.currentQuestion
    const selectedAnswers = { ...this.data.selectedAnswers }

    if (!selectedAnswers[currentIndex]) {
      selectedAnswers[currentIndex] = []
    }

    if (currentQuestion.type === 'single') {
      // 单选题
      selectedAnswers[currentIndex] = [optionKey]
    } else if (currentQuestion.type === 'multiple') {
      // 多选题
      const index = selectedAnswers[currentIndex].indexOf(optionKey)
      if (index > -1) {
        selectedAnswers[currentIndex].splice(index, 1)
      } else {
        selectedAnswers[currentIndex].push(optionKey)
      }
    }

    this.setData({ selectedAnswers })
  },

  // 上一题
  prevQuestion() {
    if (this.data.currentIndex > 0) {
      const newIndex = this.data.currentIndex - 1
      this.setData({
        currentIndex: newIndex,
        currentQuestion: this.data.questions[newIndex]
      })
    }
  },

  // 下一题
  nextQuestion() {
    if (this.data.currentIndex < this.data.questions.length - 1) {
      const newIndex = this.data.currentIndex + 1
      this.setData({
        currentIndex: newIndex,
        currentQuestion: this.data.questions[newIndex]
      })
    }
  },

  // 跳转到指定题目
  goToQuestion(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: index,
      currentQuestion: this.data.questions[index]
    })
  },

  // 显示提交确认弹窗
  showSubmitDialog() {
    this.setData({ showSubmitDialog: true })
  },

  // 关闭提交确认弹窗
  closeSubmitDialog() {
    this.setData({ showSubmitDialog: false })
  },

  // 提交考试
  submitExam() {
    this.setData({ showSubmitDialog: false })
    this.doSubmitExam()
  },

  // 时间到自动提交
  autoSubmitExam() {
    this.setData({ showTimeUpDialog: false })
    this.doSubmitExam()
  },

  // 执行提交考试
  doSubmitExam() {
    wx.showLoading({ title: '提交中...' })

    // 清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }

    const answers = Object.keys(this.data.selectedAnswers).map(index => ({
      question_id: this.data.questions[index].id,
      answers: this.data.selectedAnswers[index]
    }))

    wx.request({
      url: `${app.globalData.baseUrl}/exams/${this.data.examId}/submit`,
      method: 'POST',
      data: {
        exam_record_id: this.data.recordId,
        answers: answers,
        duration: Math.floor((this.data.totalTime - this.data.remainingTime) / 60)
      },
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data.success) {
          const { record_id } = res.data.data
          
          wx.hideLoading()
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          })

          // 跳转到考试结果页面
          setTimeout(() => {
            wx.redirectTo({
              url: `/pages/exam-result/exam-result?record_id=${record_id}`
            })
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('提交考试失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 格式化时间
  formatTime(seconds) {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    } else {
      return `${minutes}:${secs.toString().padStart(2, '0')}`
    }
  },

  // 获取题目类型文本
  getQuestionTypeText(type) {
    const typeMap = {
      'single': '单选题',
      'multiple': '多选题',
      'true_false': '判断题'
    }
    return typeMap[type] || '未知类型'
  },

  // 计算已答题数量
  computed: {
    answeredCount() {
      return Object.keys(this.data.selectedAnswers).length
    }
  }
}) 